import _ from 'underscore';
import React from 'react';
import classnames from 'classnames';
import Modal from 'lib/components/Modal.jsx';
import { defaultApi, defaultPostApi } from '../apis/core-util';
import Loading from 'lib/util/defaultLoadingElement.jsx';
import NoDataElement from 'lib/util/defaultNoDataElement.jsx';
import { Warning, Success } from 'lib/components/Notify.jsx';

const TYPES = {
  'number': '数字',
  'string': '字符串',
  'list': '集合',
  'date': '日期',
  'datetime': '时间',
  'bool': '布尔值',
  'list': '集合'
};

class UserPropertyModal extends Modal {

  constructor(props) {
    super(props);

    this.state = {
      customProperties: [],
      presetProperties: [],
      loading: true,
      pending: false
    };

    this.api = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/property/user/properties`,
      cache: false,
      show_all: true
    });

    this.error = false;
  }

  componentWillMount() {
    this.api.fetch().then((response) => {
      let customProperties = [],
          presetProperties = [];

      _.forEach(response, (property, index) => {
        if (/^\$/.test(property.name)) {
          presetProperties.push(property);
        } else {
          customProperties.push(property);
        }
      });

      this.state.customProperties = customProperties;
      this.state.presetProperties = presetProperties;
    }).always(() => {
      this.setState({
        loading: false
      });
    });
  }

  renderHeader() {
    return (
      <h4>编辑用户属性</h4>
    );
  }

  handleCNameUpdate(index, {target}) {
    let { customProperties } = this.state,
        property = customProperties[index];

    let inputValue = target.value.trim();

    if (inputValue.length < 1 || inputValue.length > 100) {
      target.style.border = '1px red solid';
      this.error = true;
    } else {
      target.style.border = '';
      property.cname = target.value.trim();
      this.error = false;

      this.setState({
        customProperties: [
          ...customProperties.slice(0, index),
          property,
          ...customProperties.slice(index + 1)
        ]
      });
    }
  }

  handleSubmitProperties() {
    if (this.error === false) {
      defaultPostApi({
        __url: `sd/${ BlueWare.appId }/api/property/user/properties`
      }).post(config => {
        let data = _.map(this.state.customProperties, (property) => {
          return {
            property_id: property.id,
            cname: property.cname
          };
        });
        config.data = JSON.stringify({
          property: data
        });
        config.contentType = 'application/json';
        Success('保存成功');

        return config;
      }).progress(() => {
        this.setState({
          pending: true
        });
      }).fail(() => {
        Warning('保存失败');
      }).done(() => {
        this.close();
      });
    }
  }

  renderBody() {
    if (this.state.loading) {
      return (
        <div className="user-property-modal-section">
          <Loading />
        </div>
      );
    }

    return (
      <div className="user-property-modal-section">
        <div className="user-property-card">
          <h5><span style={{ fontWeight: 'bold' }}>自定义属性</span> <i className="iconfont" data-tip="编辑自定义属性的名称">&#xe663;</i></h5>
          <table className="custom-property-table">
            <thead>
              <tr>
                <th width="30%">属性名</th>
                <th>显示名</th>
                <th width="30%">数据类型</th>
              </tr>
            </thead>
            <tbody>
              {
                this.state.customProperties.length === 0 ? (
                  <tr>
                    <td colSpan="3">
                      <NoDataElement content="暂无预置属性" />
                    </td>
                  </tr>
                ) : this.state.customProperties.map((property, index) => {
                  return (
                    <tr key={ index }>
                      <td>{ property.name }</td>
                      <td><input type="text" className="input-text" onChange={ this.handleCNameUpdate.bind(this, index) } defaultValue={ property.cname } /></td>
                      <td className="text-light">{ TYPES[property.data_type] }</td>
                    </tr>
                  )
                })
              }
            </tbody>
          </table>
        </div>
        <div className="user-property-card">
          <h5><span style={{ fontWeight: 'bold' }}>预置属性</span> <i className="iconfont" data-tip="这里是预置的默认属性">&#xe663;</i></h5>
          <table>
            <thead>
              <tr>
                <th width="30%">属性名</th>
                <th>显示名</th>
                <th width="30%">数据类型</th>
              </tr>
            </thead>
            <tbody>
              {
                this.state.presetProperties.length === 0 ? (
                  <tr>
                    <td colSpan="3">
                      <NoDataElement content="暂无预置属性" />
                    </td>
                  </tr>
                ) : this.state.presetProperties.map((property, index) => {
                  return (
                    <tr key={ index }>
                      <td>{ property.name }</td>
                      <td>{ property.cname }</td>
                      <td className="text-light">{ TYPES[property.data_type] }</td>
                    </tr>
                  )
                })
              }
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  renderFooter() {
    return (
      <div className="text-right">
        <a href="" style={{ marginRight: 15 }}>取消</a>
        <a href="javascript:;" disabled={ this.state.pending } className={
          classnames({
            'btn-green': this.state.pending === false,
            'btn-disabled': this.state.pending
          })
        } onClick={ this.handleSubmitProperties.bind(this) }>保存</a>
      </div>
    );
  }
}

export default UserPropertyModal;
